package com.inspectortime.admin;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.RandomStringUtils;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

public class ExceptionResolver implements HandlerExceptionResolver {

	private Log log = LogFactory.getLog(ExceptionResolver.class);
	
	private String errorView;
	private boolean live;
	
	public String getErrorView() {
		return errorView;
	}

	public boolean isLive() {
		return live;
	}

	public void setLive(boolean live) {
		this.live = live;
	}

	public void setErrorView(String errorView) {
		this.errorView = errorView;
	}

	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object source,
			Exception exception) {
		
		String reference = RandomStringUtils.randomAlphanumeric(10).toUpperCase();
		log.error("Exception reference: " + reference, exception);
		
		ModelAndView mv = new ModelAndView(errorView);
		mv.addObject("logExceptionTime", new Date());
		mv.addObject("logExceptionID", reference);
		if (!live) {
			String stack = ExceptionUtils.getFullStackTrace(exception).replaceAll("\n", "<br>");			
			mv.addObject("logException", stack);	
			mv.addObject("logExceptionMessage", exception.getMessage());
		}		
		return mv;
	}

}
